import QtQuick 2.15
import QtQuick.Layouts 1.15
import org.ukui.quick.widgets 1.0
import org.ukui.quick.items 1.0
import QtQuick.Controls 2.15
import QtQuick.Controls 2.15 as Controls

WidgetItem {
    id: rootWidget
    Layout.fillHeight: true
    clip: false

    RowLayout {
        anchors.centerIn: parent
        spacing: 5

        RowLayout {
            spacing: 2

            TextField {
                id: hueInput
                
                placeholderText: "H (0-360)"
                validator: RegExpValidator { regExp: /^(3[0-5][0-9]|[12]?[0-9][0-9]?)$/ }
            }

            TextField {
                id: saturationInput
                
                placeholderText: "S (0-1)"
                validator: RegExpValidator { regExp: /^(0(\.[0-9]+)?|1(\.0+)?)$/ }
            }

            TextField {
                id: valueInput
                
                placeholderText: "V (0-1)"
                validator: RegExpValidator { regExp: /^(0(\.[0-9]+)?|1(\.0+)?)$/ }
            }
        }

        Button {
            text: "转换"
            width: 30
            onClicked: {
                var h = parseFloat(hueInput.text);
                var s = parseFloat(saturationInput.text);
                var v = parseFloat(valueInput.text);
                var rgb = hsvToRgb(h, s, v);
                rgbOutput.text = `R: ${rgb.r.toFixed(0)}, G: ${rgb.g.toFixed(0)}, B: ${rgb.b.toFixed(0)}`;
            }
        }

        Text {
            id: rgbOutput
            width: 100 // 调整宽度以适应横向布局
            horizontalAlignment: Text.AlignHCenter
            font.pixelSize: 10
        }
    }

    function hsvToRgb(h, s, v) {
        h /= 360;
        var r, g, b;

        var i = Math.floor(h * 6);
        var f = h * 6 - i;
        var p = v * (1 - s);
        var q = v * (1 - f * s);
        var t = v * (1 - (1 - f) * s);

        switch (i % 6) {
            case 0: r = v, g = t, b = p; break;
            case 1: r = q, g = v, b = p; break;
            case 2: r = p, g = v, b = t; break;
            case 3: r = p, g = q, b = v; break;
            case 4: r = t, g = p, b = v; break;
            case 5: r = v, g = p, b = q; break;
        }

        return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
    }
}
